package com.zy.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

//Druid工具类
/*1、提供静态代码块加载配置文件，初始化连接池对象
2、提供方法
   * 获取连接的方法：通过数据库连接池获取连接
   * 释放资源
   * 获取连接池的方法
*/

public class DruidToolClass
{
    private  static DataSource ds;
    //加载配置文件
    static
    {
        try
        {
            Properties proper=new Properties();
            proper.load(DruidToolClass.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds= DruidDataSourceFactory.createDataSource(proper);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException
    {
        return ds.getConnection();
    }
    //释放资源
    public static void close(PreparedStatement sta,Connection con)
    {
        if(sta!=null)
        {
            try
            {
                sta.close();
            } catch (SQLException throwables)
            {
                throwables.printStackTrace();
            }
        }
        if(con!=null)
        {
            try
            {
                con.close();
            } catch (SQLException throwables)
            {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(ResultSet result,PreparedStatement sta, Connection con)
    {
        if(result!=null)
        {
            try
            {
                result.close();
            } catch (SQLException throwables)
            {
                throwables.printStackTrace();
            }
        }
        close(sta,con);
    }

    //返回数据源对象
    public static DataSource getDataSource()
    {
        return ds;
    }
}
